import cssVars from 'css-vars-ponyfill';
export () => {};
export type ThemeType = keyof typeof THEME;

export const THEME = {
  light: {
    '--left-bar-bg': 'white', // 这里是存放自己定义的主题变量内容
  },
  dark: {
    '--left-bar-bg': 'black',
  },
  orange: {
    '--left-bar-bg': 'orange',
  },
  normal: {
    '--left-bar-bg': '#226EE7',
  },
};

export const setTheme = (themeKey: any) => {
  const themeKeys = Object.keys(THEME);
  let KEY: ThemeType;
  if (themeKeys.includes(themeKey)) {
    KEY = themeKey;
  } else {
    KEY = (localStorage.getItem('theme') as ThemeType | undefined) || 'light';
  }

  localStorage.setItem('theme', KEY);

  let styleLink = document.getElementById('theme-style') as HTMLLinkElement;
  const hrefSrc = `/theme/${KEY}.css`;

  if (styleLink) {
    styleLink.href = hrefSrc;
  } else {
    styleLink = document.createElement('link');
    styleLink.type = 'text/css';
    styleLink.rel = 'stylesheet';
    styleLink.id = 'theme-style';
    styleLink.href = hrefSrc;
    document.body.append(styleLink);
  }

  cssVars({
    onlyLegacy: false,
    variables: THEME[KEY],
    onError() {
      cssVars({
        onlyLegacy: false,
        variables: THEME[KEY],
      });
    },
  });
};
